﻿using Huanan.Algorithm.DSP;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace WpfApp1
{
    /// <summary>
    /// HRV12ECG.xaml 的交互逻辑
    /// </summary>
    public partial class HRV12ECG : Window
    {
        public HRV12ECG()
        {
            InitializeComponent();
        }
        private void DrawECG()
        {

            int width = (int)outCanvasecg.ActualWidth;
            int height = (int)outCanvasecg.ActualHeight;
            if (width > 0 && height > 0)
            {
                DisplayIamgeECG.Width = width;
                DisplayIamgeECG.Height = height;
                wBitmapecg = new WriteableBitmap(width, height, 72, 72, PixelFormats.Bgr24, null);
                DisplayIamgeECG.Source = wBitmapecg;
            }
            wBitmapecg.Lock();
            Bitmap backBitmap = new Bitmap(width, height, wBitmapecg.BackBufferStride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, wBitmapecg.BackBuffer);
            Graphics graphics = Graphics.FromImage(backBitmap);
            graphics.Clear(System.Drawing.Color.Gray);

            int leadIndex = btmlead.SelectedIndex;

            double Speed = double.Parse(btmSpedd.Text);

            double AP = double.Parse(btmApmlity.Text);

            //for (int i = 0; i < hrates.Count - 1; i++)
            //{
            //    graphics.DrawLine(Pens.Red, i * 2, 200 - (hrates[i].heartrate - 60) * 4, (i + 1) * 2, 200 - (hrates[i + 1].heartrate - 60) * 4);
            //}
            int OnemmPex = 4;

            //绘制网格 

            int nwide = width / OnemmPex;

            int nhighte = height / OnemmPex;

            for (int i = 0; i < nwide; i++)
            {

                graphics.DrawLine(Pens.Black, i * OnemmPex, 0, i * OnemmPex, nhighte * OnemmPex);

            }
            for (int i = 0; i < nhighte; i++)
            {

                graphics.DrawLine(Pens.Black, 0, i * OnemmPex, nwide * OnemmPex, i * OnemmPex);

            }

            double dis = Speed * OnemmPex /500;

            int DrawLeng = (int)(width / dis);
            int currentIdnex = (int)slider.Value * 100;
            for (int i = 0; i < DrawLeng; i++)
            {
                
                if (currentIdnex + i < ecglistdata .Count- 1)
                {
                      graphics.DrawLine(Pens.Red, (float)(i * dis), (float)(150 - ecglistdata[currentIdnex + i]/10), (float)((i + 1) * dis), (float)(150 - ecglistdata[currentIdnex + i + 1]/10 ));
                    //graphics.DrawLine(Pens.Red, i, 150 , i + 1, 150 );
                }

            }

            Font drawFont = new Font("Arial", 8);
            SolidBrush drawBrush = new SolidBrush(System.Drawing.Color.Yellow);

            graphics.DrawString(btmlead.Text, drawFont, drawBrush, 5, 10);

            graphics.Flush();
            graphics.Dispose();
            graphics = null;
            backBitmap.Dispose();
            backBitmap = null;
            wBitmapecg.AddDirtyRect(new Int32Rect(0, 0, width, height));
            wBitmapecg.Unlock();
        }


        public void ReadData1(string datapath)
        {
            if (!File.Exists(datapath))
            {
                return;
            }

            FileStream fs = new FileStream(datapath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader binReader = new BinaryReader(fs);
            byte[] verifyArray = binReader.ReadBytes((int)fs.Length);
            long dataLength = fs.Length / sizeof(double);
            double[] ecgSourceData;
            ecgSourceData = new double[dataLength];
            double[] ecgSourceDataShort = new double[dataLength];
            Buffer.BlockCopy(verifyArray, 0, ecgSourceDataShort, 0, verifyArray.Length);
            for (int i = 0; i < dataLength; i++)
            {
                ecgSourceData[i] = (double)ecgSourceDataShort[i];
            }
            fs.Close();
            binReader.Close();

            singleDataLength = Convert.ToInt32(dataLength / leadCount);

            ecgData = new double[leadCount][];

            for (int i = 0; i < leadCount; i++)
            {
                ecgData[i] = new double[singleDataLength];

            }

            for (int i = 0; i < leadCount; i++)
            {
                for (int j = 0; j < singleDataLength; j++)
                {
                    ecgData[i][j] = ecgSourceData[2+j * leadCount + i] ;
                }
            }

        }

        public void ReadData(string datapath)
        {
            if (!File.Exists(datapath))
            {
                return;
            }
            ecglistdata.Clear();
            StreamReader reader = new StreamReader(datapath);
            string conent = reader.ReadToEnd();
            var liststr = new List<string>(conent.Split(' ')).ToList();
            ecglistdata = liststr.Select<string ,int>(x=>Convert.ToInt32(x)).ToList();
            for (int i = 0; i < 3; i++)
            {
                ecgData[i] = new double[liststr.Count()];

            }

            for (int i=0;i< liststr.Count();i++)
            {
                ecgData[0][i] = ecgData[0][1] = ecgData[0][2] = Convert.ToInt32(liststr[i]);
            }

            reader.Close();

        }
        DispatcherTimer timer = new DispatcherTimer();
        private WriteableBitmap wBitmapecg;

        int leadCount = 16;
        double[][] ecgData =new double[3][];
        int singleDataLength = 0;
        List<int> ecglistdata = new List<int>();
        private void btmEcgpath_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();

            if (op.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                string ecgpath = op.FileName;

                Dispatcher.BeginInvoke(new Action(() =>
                {

                    ReadData(ecgpath);
                    DrawECG();

                }));
            }

            timer.Start();

           


        }

        private void btncancelCal_Click(object sender, RoutedEventArgs e)
        {
            // 统计心率 

            

        }

        private void btnCalHr_Click(object sender, RoutedEventArgs e)
        {
            HeartBeatInfoVector hbiv = new HeartBeatInfoVector();//所有心拍信息

            // ECGAlgHelper.FindAllHeartBeats(hbiv, 0, ecgData);
            HNAlgoNative.FindAllFrankHeartBeats(hbiv, (uint)ecglistdata.Count, ecgData[0], ecgData[1], ecgData[2]);

        }

        private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            DrawECG();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            timer.Tick += Timer_Tick;
            timer.Interval = TimeSpan.FromMilliseconds(100);
        }
        int packcount = 100;
        int pack;
        int nQrspos = 0;
        int preqrspos = 0;

        CalHeartRate calHeart = new CalHeartRate();
        List<string > lsithr = new List<string>();
        Dictionary<int, int> dictecg=new Dictionary<int, int>();
        private void Timer_Tick(object sender, EventArgs e)
        {
            //模拟实时计算心率

            int Heartrate = 0;
            double[] dinput = new double[packcount];
            if (pack < ecglistdata.Count / packcount - 1)
            {
                for (int j = 0; j < packcount; j++)
                {
                    //抽点降采样率
                    dinput[j] = ecglistdata[pack * packcount + j ];

                    //计算平均值降采样率
                    // dinput[j] = (ecgData[1][pack * packcount + j*4]+ecgData[1][pack * packcount + j * 4 + 1]+ecgData[1][pack * packcount + j * 4 + 2]+ ecgData[1][pack * packcount + j * 4 + 3])/4;
                }

                Thread.Sleep(10);
               
                Heartrate = calHeart.GetVCGParameter(dinput, packcount, out nQrspos);
                
                Dispatcher.BeginInvoke(new Action(() =>
                {

                    txtCalHr.Text = (Heartrate*2).ToString() + "-" + (pack * packcount + nQrspos).ToString();
                   

                    if (preqrspos < pack * packcount + nQrspos&& Heartrate>0)
                    {
                        lsithr.Add(txtCalHr.Text);
                        preqrspos = pack * packcount + nQrspos;
                        dictecg.Add(pack * packcount + nQrspos, Heartrate * 2);
                    }


                }));
            }
            else
            {
                timer.Stop();
                pack = 0;

                comboxheatrate.ItemsSource = lsithr;
            }
            pack++;
        }
    }
}
